package rexsee.core.browser.clazz;

import rexsee.core.browser.Browser;
import rexsee.core.browser.clazz.ActivityResult.ActivityResultListener;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;

public class FileSelector {

	public static final String FILE_TYPE_IMAGE = "image";
	public static final String FILE_TYPE_AUDIO = "audio";
	public static final String FILE_TYPE_VIDEO = "video";

	private final Browser mBrowser;
	private final Context mContext;

	public FileSelector(Browser browser) {
		super();
		mBrowser = browser;
		mContext = browser.getContext();
	}

	public static abstract class FileSelecteListener {
		public abstract void run(String path, String errorMessage);
	}

	private String getType(String type) {
		if (type == null || type.equals("")) {
			return "*/*";
		} else if (type.equals(FILE_TYPE_IMAGE)) {
			return "image/*";
		} else if (type.equals(FILE_TYPE_AUDIO)) {
			return "audio/*";
		} else if (type.equals(FILE_TYPE_VIDEO)) {
			return "video/*";
		} else {
			return type;
		}
	}
	private String getPath(Uri uri) {
		String scheme = uri.getScheme();
		String path = uri.getPath();
		if (scheme == null) return "";
		else if (scheme.equals("file")) return "file://" + path;
		else if (scheme.equals("content")) {
			String id = uri.getLastPathSegment();
			String db = "content://" + uri.getHost() + path.substring(0, path.lastIndexOf("/"));
			ContentResolver contentResolver = mContext.getContentResolver();
			Cursor cursor = contentResolver.query(Uri.parse(db), new String[]{"_data"}, " _id=?", new String[]{id}, null);
			if (cursor == null || cursor.getCount() == 0) return "";
			cursor.moveToFirst();
			String rtn = "file://" + cursor.getString(0);
			cursor.close();
			return rtn;
		} else return "";
	}
	public void selectByDefault(String type, final FileSelecteListener listener) {
		Intent intent = new Intent();
		intent.setAction(Intent.ACTION_GET_CONTENT);
		intent.setType(getType(type));
		intent.addCategory(Intent.CATEGORY_OPENABLE);
		mBrowser.activityResult.start(intent, new ActivityResultListener() {
			@Override
			public void run(int resultCode, Intent resultIntent) {
				try {
					if (resultCode == Activity.RESULT_OK) {
						listener.run(getPath(resultIntent.getData()), "");
					} else {
						listener.run(null, "User canceled.");
					}
				} catch (Exception e) {
					listener.run(null, e.getLocalizedMessage());
				}
			}
		});
	}

}
